// global variable to store list of open URLs
var gOpenUrlList = [];

// function to get list of open URLs
function list_session(callback) {
    chrome.windows.getAll({populate : true}, function (window_list) {
        var list = [];
        for(var i=0;i<window_list.length;i++) {
            list = list.concat(window_list[i].tabs);
        }
        //console.log(list);
        if(callback) {
            callback(list);
        }
    });
};

// function to get list of open URLs
// this function is not used - "works" but gives same result as list_sessions, and runs asynchronous....
function getAllOpenWindows(winData) {
  var tabs = [];
  for (var i in winData) {
    if (winData[i].focused === true) {
        var winTabs = winData[i].tabs;
        var totTabs = winTabs.length;
        for (var j=0; j<totTabs;j++) {
			// trim url down example : ( http://www.mbl.is/frettir  to http://www.mbl.is )
			// Find zero or more alpha characters followed by a colon (the protocol, which can be omitted)
			// Followed by // (can also be omitted)
			// Followed by any characters except / (the hostname and port)
			// Followed by /
			// Followed by whatever (the path, less the beginning /).
			var baseUrl = winTabs[j].url.match(/^(([a-z]+:)?(\/\/)?[^\/]+\/).*$/)[1];
			tabs.push(baseUrl);
			// push to global variable
			gOpenUrlList.push(baseUrl);
        }
    }
  }
  //console.log(gOpenUrlList);
  //console.log(gOpenUrlList.length);
};

function searchStringInArray (str, strArray) {
    // this loop seems to run zero (0) times....
	for (var j in strArray) {
        //console.log(strArray[j]);
		//console.log(str);
		if (strArray[j].match(str)) return j;
    }
    return -1;
};

function onButtonPressed()
{
    var newsUrls = ["http://www.dv.is", "http://www.pressan.is","http://www.mbl.is","http://www.visir.is"];
   	var openUrlList = [];
	var lengthx = 0;
	list_session(function(tab_list) {
		//use array of tabs
		//console.log(tab_list.length);
		lengthx = tab_list.length;
		for (var x=0; x < lengthx; x++) {
			//console.log(tab_list[x].url);
			var baseUrl = tab_list[x].url.match(/^(([a-z]+:)?(\/\/)?[^\/]+\/).*$/)[1];	
			gOpenUrlList.push(baseUrl);
			//console.log(baseUrl);
		}
	});
	// open news pages
	for (var i in newsUrls) {
		var url = newsUrls[i];
		// only open page if it is not already open
		// does not work....
		var pageOpen = searchStringInArray(url, openUrlList);
		if (pageOpen === -1) {
			chrome.tabs.create({"url": url });
		}
    }
};

chrome.browserAction.onClicked.addListener(onButtonPressed);